// index.js
import { apiGetWebsite } from '@/api/website'
import { useErrMessage } from '@/utils/message'
import { apiGetUserInfo } from '@/api/user'
import { apiFirstRez } from '@/api/reservation'

Page({
  data: {
    indexCover: "http://8.138.85.156/assets/grs/indexCover.png",
    websiteInfo: null,
    loading: false,
    error: null,
    showQrModal: false,
    qrImg: ''
  },

  onLoad() {
    this.checkAndLoadWebsiteData();
    this.loadUser()
  },

  async loadUser() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      const data = await apiGetUserInfo()
      wx.setStorageSync('userInfo', data.data)
    }
  },

  async checkAndLoadWebsiteData() {
    // 先检查内存中是否有数据
    if (this.data.websiteInfo === null) {
      try {
        // 尝试从本地存储获取
        const storedData = wx.getStorageSync('websiteInfo');
        if (storedData) {
          // 如果存储中有数据，更新到内存
          this.setData({
            websiteInfo: storedData
          });
          return;
        }
      } catch (e) {
        console.error('读取本地存储失败:', e);
      }

      // 如果存储中没有数据，从网络加载
      await this.loadWebsiteData();
    }
  },

  async loadWebsiteData() {
    this.setData({ loading: true, error: null });

    try {
      const data = await apiGetWebsite();
      if (data.code === 200) {
        this.setData({
          websiteInfo: data.data,
          loading: false
        });
        wx.setStorageSync('websiteInfo', data.data);
      } else {
        useErrMessage(this, data.msg)
      }
    } catch (error) {
      this.setData({
        error: error,
        loading: false
      });
    }
  },
  onShow() {
    this.checkAndLoadWebsiteData();
  },
  async showQRCode() {
    const res = await apiFirstRez()
    
    if (res.code === 200) {
      const data = res.data
      const qrImg = 'data:image/png;base64,' + data.qr
      this.setData({
        showQrModal: true,
        qrImg: qrImg,
        qrTitle: `${data.name}-第${data.number}号场`
      })
    }else if(res.code === 4003){
      useErrMessage(this, "暂无最新预约信息，请去预约场地吧")
    }
  },
  closeQrModal() {
    this.setData({
      showQrModal: false,
      qrImg: ''
    })
  }
})
